package com.hsq.ndmall.wx.service;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import com.hsq.ndmall.common.utils.CouponUserConstant;
import com.hsq.ndmall.common.utils.ListFromEntity2VoUtils;
import com.hsq.ndmall.common.utils.R;
import com.hsq.ndmall.wx.feign.order.*;
import com.hsq.ndmall.wx.utils.OrderUtil;
import com.hsq.ndmall.wx.vo.groupon.GrouponRulesVo;
import com.hsq.ndmall.wx.vo.order.CartVo;
import com.hsq.ndmall.wx.vo.order.OrderGoods;
import com.hsq.ndmall.wx.vo.order.OrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 黄四清
 * @version 1.0.0
 * @ClassName OrderService.java
 * @Description TODO
 * @createTime 2021年08月22日 13:16:00
 */
@Service
@Slf4j
public class OrderService {

    @Autowired
    OrderFeign orderFeign;

    @Autowired
    PromotionFeign promotionFeign;

    @Autowired
    UserFeign userFeign;

    @Autowired
    MallFeign mallFeign;

    @Autowired
    ProductFeign productFeign;


    @Transactional
    public R createOrder(Integer id, Map<String, Object> params) {

        Map<String, Object> paramMap = new HashMap<>();
        Integer orderId = null;
        // TODO 1、参数
        if (id == null) {
            return R.badArgument();
        }
        try {
            // TODO 2、MapUtil解析数据
            Integer userId = id;
            Integer cartId = MapUtil.get(params, "cartId", Integer.class);
            Integer addressId = MapUtil.get(params, "addressId", Integer.class);
            Integer couponId = MapUtil.get(params, "couponId", Integer.class);
            Integer userCouponId = MapUtil.get(params, "userCouponId", Integer.class);
            String message = MapUtil.get(params, "message", String.class);
            Integer grouponRulesId = MapUtil.get(params, "grouponRulesId", Integer.class);
            Integer grouponLinkId = MapUtil.get(params, "grouponLinkId", Integer.class);

            //TODO 3、如果是团购项目,验证活动是否有效
            R grouponInfo = null;
            GrouponRulesVo grouponRules = null;  // 团购对象
            if (grouponRulesId != null && grouponRulesId > 0) {
                grouponInfo = promotionFeign.grouponInfo(grouponRulesId);
                // 拿到团购对象
                grouponRules = MapUtil.get(grouponInfo, "grouponRules", GrouponRulesVo.class);
                //找不到记录
                if (grouponRules == null) {
                    return R.badArgument();
                }
                //团购活动已经过期
                // return R.ok(grouponInfo);
            }
            // TODO 4、检验是否为购物车提交是否填写了收获地址是否带优惠券id (-1没有使用优惠券)
            if (cartId == null || addressId == null || couponId == null) {
                return R.badArgument();
            }

            // TODO 5、收货地址
            paramMap.put("id", addressId);
            R addressR = userFeign.addresslist(paramMap);

            // TODO 6、计算团购优惠金额
            BigDecimal grouponPrice = new BigDecimal(0.00);
            if (grouponRulesId != null && grouponRulesId > 0) {
                if (grouponRules != null) {
                    // 得到团购的优惠金额
                    grouponPrice = new BigDecimal(grouponRules.getDiscount());
                }
            }

            //TODO 7、获取付款的购物车信息  货品价格
            List<CartVo> checkedGoodsList = null;
            if (cartId.equals(0)) {
                paramMap.clear();
                paramMap.put("user_id", userId);
                R list = orderFeign.list(paramMap);
                List<Map> orderList = (List<Map>) ((Map) list.get("page")).get("list");
                List<CartVo> cartVos = ListFromEntity2VoUtils.entity2Vo(orderList, CartVo.class);
                checkedGoodsList = cartVos;
            } else {
                paramMap.clear();
                paramMap.put("id", cartId);
                R CartR = orderFeign.list(paramMap);
                // 查询不到这个购物车ID，则返回参数不对
                if (MapUtil.get((Map) CartR.get("page"), "list", List.class) == null) {
                    return R.badArgument();
                }
                checkedGoodsList = new ArrayList<>(1);
                List<Map> orderList = (List<Map>) ((Map) CartR.get("page")).get("list");
                List<CartVo> cartVos = ListFromEntity2VoUtils.entity2Vo(orderList, CartVo.class);
                checkedGoodsList = cartVos;
            }
            // 购物车信息为空，直接返回参数错
            if (checkedGoodsList.size() == 0) {
                return R.badArgumentValue();
            }

            // TODO 8、计算货品的价格
            BigDecimal checkedGoodsPrice = new BigDecimal(0.00);
            for (CartVo cart : checkedGoodsList) {
                //  只有当团购规格商品ID符合才进行团购优惠
                if (grouponRules != null && grouponRules.getGoodsId().equals(cart.getGoodsId())) {
                    // checkedGoodsPrice +=  （购物车商品的价格-团购优惠的金额） * 商品的数量
                    checkedGoodsPrice = checkedGoodsPrice.add(cart.getPrice().subtract(grouponPrice).multiply(new BigDecimal(cart.getNumber())));
                } else {
                    // 没有团购信商品ID checkedGoodsPrice += （购物车商品的价格 * 商品的数量）
                    checkedGoodsPrice = checkedGoodsPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
                }
            }

            // TODO 9、 获取可用的优惠券信息  检测优惠券是否可用，可用则，使用优惠券减免的金额
            BigDecimal couponPrice = new BigDecimal(0.00);
            // 如果couponId=0则没有优惠券，couponId=-1则不使用优惠券
            if (couponId != 0 && couponId != -1) {
                R couponInfo = promotionFeign.couponInfo(couponId);
                if (couponInfo == null) {
                    return R.badArgumentValue();
                }
                couponPrice = new BigDecimal(((Map) couponInfo.get("coupon")).get("discount").toString());
            }

            // TODO 10、根据订单商品总价计算运费
            // 根据订单商品总价计算运费，满88则免运费，否则8元；
            BigDecimal freightPrice = new BigDecimal(0.00);
            if (checkedGoodsPrice.compareTo(MapUtil.get(mallFeign.getFreightLimit(), "freight_limit", BigDecimal.class)) < 0) {
                freightPrice = MapUtil.get(mallFeign.getFreight(), "freight", BigDecimal.class);
            }

            // 13.可以使用的其他钱，例如用户积分
            BigDecimal integralPrice = new BigDecimal(0.00);

            // 14.订单费用
            BigDecimal orderTotalPrice = checkedGoodsPrice.add(freightPrice).subtract(couponPrice).max(new BigDecimal(0.00));

            // 15.创建订单
            OrderVo order = new OrderVo();
            order.setUserId(userId);
            order.setOrderSn(OrderUtil.generateOrderSn(userId));
            List<Map> addressList = (List<Map>) ((Map) addressR.get("page")).get("list");
            order.setOrderStatus(OrderUtil.STATUS_CREATE);
            // order.setOrderStatus(new Short("101"));
            order.setConsignee(MapUtil.get((Map) addressList.get(0), "name", String.class));
            order.setMobile(MapUtil.get((Map) addressList.get(0), "tel", String.class));
            order.setMessage(message);
            String detailedAddress = MapUtil.get((Map) addressList.get(0), "province", String.class) +
                    MapUtil.get((Map) addressList.get(0), "city", String.class) +
                    MapUtil.get((Map) addressList.get(0), "county", String.class) +
                    MapUtil.get((Map) addressList.get(0), "addressDetail", String.class);
            order.setAddress(detailedAddress);
            order.setGoodsPrice(checkedGoodsPrice);
            order.setFreightPrice(freightPrice);
            order.setCouponPrice(couponPrice);
            order.setIntegralPrice(integralPrice);
            order.setOrderPrice(orderTotalPrice);
            order.setActualPrice(orderTotalPrice);
            // 有团购活动
            if (grouponRules != null) {
                order.setGrouponPrice(grouponPrice);    //  团购价格
            } else {
                order.setGrouponPrice(new BigDecimal(0.00));    //  团购价格
            }
            //16. 创建订单
            R orderSave = orderFeign.orderSave(order);
            orderId = MapUtil.get(orderSave, "orderId", Integer.class);


            // 17、添加订单商品表项
            for (CartVo cartVo : checkedGoodsList) {
                OrderGoods orderGoods = new OrderGoods();
                orderGoods.setOrderId(orderId);
                orderGoods.setGoodsId(cartVo.getGoodsId());
                orderGoods.setGoodsSn(cartVo.getGoodsSn());
                orderGoods.setProductId(cartVo.getProductId());
                orderGoods.setGoodsName(cartVo.getGoodsName());
                orderGoods.setPicUrl(cartVo.getPicUrl());
                orderGoods.setPrice(cartVo.getPrice());
                orderGoods.setNumber(cartVo.getNumber());
                orderGoods.setSpecifications(ArrayUtil.join(cartVo.getSpecifications(), ","));
                orderGoods.setAddTime(LocalDateTime.now());
                orderFeign.orderGoodsSave(orderGoods);
            }

            // 18.删除购物车里面的商品信息
            //cartService.clearGoods(userId);
            //int a = 10 / 0;
            //19. 商品货品数量减少
            for (CartVo cartVo : checkedGoodsList) {
                Integer productId = cartVo.getProductId();
                R product = productFeign.findProductById(productId);

                Short lockNumber = (short) ((int) cartVo.getNumber());
                if (lockNumber < 0) {
                    throw new RuntimeException("下单的商品货品数量大于库存量");
                }
//            if(Integer.parseInt(productFeignClient.reduceStock(orderId,productId, lockNumber).get("errno").toString())==500){
//                throw new RuntimeException("商品货品库存减少失败");
//            }
                // 修改商品数量

            }

        //20.如果使用了优惠券，设置优惠券使用状态
        if (couponId != 0 && couponId != -1) {
            R couponUser = promotionFeign.couponUserInfo(userCouponId);
            Map couponUserMap = (Map) couponUser.get("couponUser");
            couponUserMap.put("status", CouponUserConstant.STATUS_USED);
            couponUserMap.put("usedTime", LocalDateTime.now());
            couponUserMap.put("orderId", orderId);

            // int a = 10/0;
            promotionFeign.update(couponUserMap);
            System.out.println("修改优惠券的使用状态成功！");
        }

            // 21、如果时团购项目，添加团购信息
            if (grouponRulesId != null && grouponRulesId > 0) {
                Map grouponMap = new HashMap();
                grouponMap.put("orderId", orderId);
                grouponMap.put("payed", false);
                grouponMap.put("userId", userId);
                grouponMap.put("rulesId", grouponRulesId);
                //参与者
                if (grouponLinkId != null && grouponLinkId > 0) {

                } else {

                }
            }

        } catch (Exception e) {
            // 如果发生异常，则需要回滚！模拟事务回滚，肯定会有bug，先这样解决
            if (orderId != null) {
                // 则需要回滚，删除这个订单信息，
                Integer[] ids = new Integer[1];
                ids[0] = orderId;
                orderFeign.delete(ids);
                log.info("=============模拟回滚成功！！=========");
                return R.error("500,服务器错误");
            } else {
                return R.error("500,服务器错误");
            }
        }

        return R.ok().put("orderId", orderId);
    }

    public R createOrderCopy(String body) {
        //map参数转为
        //String body = JSONUtil.parse(params).toStringPretty();
        R r = orderFeign.submit(body);
        return r;
    }
}
